<template>
  <div>
    <div class="container">
      <el-form ref="query" :model="query" :inline="true" size="mini">
        <el-form-item label="状态：" prop="enabled">
          <el-select
              v-model="query.enabled"
              placeholder="请填写状态"
              clearable
              filterable
          >
            <el-option
                v-for="item in $enum.getMapItems('enabled')"
                :key="item.value"
                :label="item.name"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="手机：" prop="mobile">
          <el-input
              v-model="query.mobile"
              placeholder="请填写手机"
              clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="姓名：" prop="realName">
          <el-input
              v-model="query.realName"
              placeholder="请填写姓名"
              clearable
          ></el-input>
        </el-form-item>

        <el-button
            size="mini"
            type="primary"
            icon="el-icon-search"
            @click="handleSearch"
        >搜索
        </el-button>
        <el-button
            size="mini"
            type="primary"
            icon="el-icon-delete"
            @click="handleClear"
        >清空
        </el-button>
      </el-form>

      <div class="handle-box">
        <el-button
            size="mini"
            type="primary"
            icon="el-icon-plus"
            class="handle-del mr10"
            @click="handleEdit()"
            v-if="$perm.hasPerm('button_user_add')"
        >添加
        </el-button>

        <el-button
            size="mini"
            type="primary"
            icon="el-icon-plus"
            class="handle-del mr10"
            @click="handleEditOrgUser()"
            v-if="$perm.hasPerm('button_user_addByOrg')"
        >添加组织用户
        </el-button>
        <el-button
            size="mini"
            type="primary"
            icon="el-icon-delete"
            class="handle-del mr10"
            @click="delAllSelection()"
            v-if="$perm.hasPerm('button_user_batchDelete')"
        >批量删除
        </el-button>
      </div>

      <el-table
          :data="records"
          border
          class="table"
          ref="multipleTable"
          header-cell-class-name="table-header"
          @selection-change="handleSelectionChange"
      >
        <el-table-column
            type="selection"
            width="55"
            align="center"
        ></el-table-column>
        <el-table-column prop="jobNumber" label="工号"></el-table-column>
        <el-table-column prop="mobile" label="手机"></el-table-column>
        <el-table-column prop="realName" label="姓名"></el-table-column>
        <el-table-column prop="mail" label="邮箱"></el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-tag
                :type="
                scope.row.enabled === true
                  ? 'success'
                  : scope.row.enabled === false
                  ? 'danger'
                  : 'info'
              "
            >{{ $enum.getMapValue("enabled", scope.row.enabled).name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间"></el-table-column>
        <el-table-column prop="modifiedTime" label="更新时间"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button
                type="text"
                @click="handleEdit(scope.row.id)"
                v-if="$perm.hasPerm('button_user_edit')"
            >编辑
            </el-button>

            <el-button
                type="text"
                @click="handleEditGrantRole(scope.row.id)"
                v-if="$perm.hasPerm('button_user_editBatchRole')"
            >授权角色
            </el-button>

            <el-button
                type="text"
                @click="handleEditGrantUserGroup(scope.row.id)"
                v-if="$perm.hasPerm('button_user_editBatchUserGroup')"
            >授权用户组
            </el-button>

            <el-button
                type="text"
                @click="handleEditStatus(scope.row.id, scope.row.enabled)"
                v-if="$perm.hasPerm('button_user_editStatus')"
            >
              {{ scope.row.enabled == true ? "禁用" : "启用" }}
            </el-button>

            <el-button
                type="text"
                @click="handleEditResetGa(scope.row.id)"
                v-if="$perm.hasPerm('button_user_editResetGa') && scope.row.gaBindFlag == true"
            >
              {{ "重置GA" }}
            </el-button>

            <el-button
                type="text"
                class="red"
                @click="handleDelete(scope.$index, scope.row)"
                v-if="$perm.hasPerm('button_user_batchDelete')"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <custom-page
            :current="query.current"
            :size="query.size"
            :total="total"
            @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 授权角色弹出框 -->
    <el-dialog
        title="授权角色"
        v-model="editGrantRoleVisible"
        :rules="rules"
        ref="editGrantRole"
        width="50%"
        @closed="closed"
        @keyup.enter="editGrantRoleSubmit()"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-input v-if="visible" v-model="form.userId"/>
        <el-form-item label="所属角色" prop="roleIds">
          <el-select
              v-model="form.roleIds"
              placeholder="请填写所属角色"
              class="handle-select mr10"
              clearable
              filterable
              multiple
          >
            <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editGrantRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="editGrantRoleSubmit()"
          >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 授权用户组弹出框 -->
    <el-dialog
        title="授权用户组"
        v-model="editGrantUserGroupVisible"
        :rules="rules"
        ref="editGrantUserGroup"
        width="50%"
        @closed="closed"
        @keyup.enter="editGrantUserGroupSubmit()"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-input v-if="visible" v-model="form.userId"/>
        <el-form-item label="所属组" prop="userGroupIds">
          <el-select
              v-model="form.userGroupIds"
              placeholder="请填写所属组"
              class="handle-select mr10"
              clearable
              filterable
              multiple
          >
            <el-option
                v-for="item in userGroupList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editGrantUserGroupVisible = false">取 消</el-button>
          <el-button type="primary" @click="editGrantUserGroupSubmit()"
          >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 给组织添加用户弹出框 -->
    <el-dialog
        title="给组织添加用户"
        v-model="editOrgUserVisible"
        :rules="rules"
        ref="editOrgUser"
        width="50%"
        @closed="closed"
        @keyup.enter="editOrgUserSubmit()"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="用户" prop="userId">
          <el-select
              class="handle-select mr10"
              v-model="form.userId"
              filterable
              placeholder="请输入关键词（工号、手机、用户名、邮箱、身份证、姓名）"
              @keyup.enter.native="handleEnter"
          >
            <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.username"
                :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="departmentIds">
          <el-tree
              ref="departmentTree"
              :data="form.departments"
              show-checkbox
              node-key="id"
              :default-checked-keys="form.departmentIds"
              :props="defaultProps"
          >
          </el-tree>
        </el-form-item>
        <el-form-item label="所属职位" prop="positionIds">
          <el-select
              v-model="form.positionIds"
              placeholder="请填写所属职位"
              class="handle-select mr10"
              clearable
              filterable
              multiple
          >
            <el-option
                v-for="item in form.positions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editOrgUserVisible = false">取 消</el-button>
          <el-button type="primary" @click="editOrgUserSubmit()"
          >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  createObjectBase,
  deepCopy,
  getTreeByCheck,
  getSelectIds,
} from "@/utils";

import {
  userPageApi,
  userRemoveApi,
  userEditEnabledApi,
  userEditBatchRoleApi,
  userEditBatchUserGroupApi,
  userSaveOrgUserApi,
  userListByConditionApi,
  userEditResetGaApi,
} from "../../../api/mgt/power/user";
import {roleListByUserIdApi} from "../../../api/mgt/power/role";
import {userGroupListByUserIdApi} from "../../../api/mgt/power/userGroup";
import {departmentListByUserIdApi} from "../../../api/mgt/power/department";
import {positionListByUserIdApi} from "../../../api/mgt/power/position";

const obj = {
  userId: "",
  roleIds: [],
  userGroupIds: [],
  departmentIds: [],
  positionIds: [],
};

export default {
  data() {
    const checkDepartment = (rule, value, callback) => {
      let arr = this.$refs.departmentTree.getCheckedKeys();
      if (arr.length == 0 || !arr) {
        callback(new Error("请填写所属部门"));
      } else {
        callback();
      }
    };
    return {
      editGrantRoleVisible: false,
      editGrantUserGroupVisible: false,
      editOrgUserVisible: false,
      form: deepCopy(obj),
      defaultProps: {
        children: "children",
        value: "name",
        label: "name",
      },
      query: {
        current: 1,
        size: 10,
        enabled: null,
        mobile: null,
        realName: null,
      },
      records: [],
      multipleSelection: [],
      delList: [],
      total: 0,
      roleList: [],
      userGroupList: [],
      userList: [],
      rules: {
        userId: [{required: true, message: "请选择用户", trigger: "blur"}],
        departmentIds: [
          {required: true, validator: checkDepartment, trigger: "change"},
        ],
        positionIds: [
          {required: true, message: "请填写所属职位", trigger: "change"},
        ],
      },
    };
  },
  created() {
    this.getData();
  },
  methods: {
    // 获取数据
    getData() {
      userPageApi(this.query).then((res) => {
        this.records = res?.bizData?.records;
        this.total = res?.bizData?.total;
      });
    },
    // 触发搜索按钮
    handleSearch() {
      this.query.current = 1;
      this.getData();
    },
    // 清空
    handleClear() {
      if (this.$refs.query != undefined) {
        this.$refs.query.resetFields();
        this.getData();
      }
    },
    // 启/禁用
    handleEditStatus(id, status) {
      let tip;
      let statusVal;
      if (status == true) {
        tip = "确定要禁用吗？";
        statusVal = false;
      } else if (status == false) {
        tip = "确定要启用吗？";
        statusVal = true;
      }
      this.$confirm(tip, "提示", {
        type: "warning",
      }).then(() => {
        userEditEnabledApi({id: id, enabled: statusVal}).then((res) => {
          this.getData();
        });
      });
    },
    // 重置GA
    handleEditResetGa(id) {
      let tip = "确定要重置GA吗？";
      this.$confirm(tip, "提示", {
        type: "warning",
      }).then(() => {
        userEditResetGaApi({userId: id}).then((res) => {
          this.getData();
        });
      });
    },
    // 删除操作
    handleDelete(index, row) {
      // 二次确认删除
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      }).then(() => {
        userRemoveApi({ids: row.id}).then((res) => {
          this.getData();
        });
      });
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    delAllSelection() {
      const length = this.multipleSelection.length;
      if (length < 1) {
        this.$message.error("请选择数据");
        return;
      }
      this.multipleSelection.filter((item) => {
        this.delList.push(item.id);
      });
      const ids = this.delList.join(",");
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      }).then(() => {
        userRemoveApi({ids: ids}).then((res) => {
          this.getData();
        });
      });
    },
    // 编辑操作
    handleEdit(id) {
      this.$router.goPage({
        path: "/user/operate",
        query: {
          id,
        },
      });
    },
    getRoleList(userId) {
      roleListByUserIdApi({userId}).then((res) => {
        this.roleList = res?.bizData;
        this.form.roleIds = this.roleList
            .filter((item) => item.checked)
            .map((item) => item.id);
      });
    },
    // 授权角色
    handleEditGrantRole(id) {
      if (this.$refs.form != undefined) {
        this.$refs["form"].resetFields();
      }
      this.form.userId = id;
      this.getRoleList(id);
      this.editGrantRoleVisible = true;
    },
    // 授权角色-确认
    editGrantRoleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          userEditBatchRoleApi(this.form).then((res) => {
            this.editGrantRoleVisible = false;
          });
        } else {
          return false;
        }
      });
    },
    getUserGroupList(userId) {
      userGroupListByUserIdApi({userId}).then((res) => {
        this.userGroupList = res?.bizData;
        this.form.userGroupIds = this.userGroupList
            .filter((item) => item.checked)
            .map((item) => item.id);
      });
    },
    // 授权用户组
    handleEditGrantUserGroup(id) {
      if (this.$refs.form != undefined) {
        this.$refs["form"].resetFields();
      }
      this.form.userId = id;
      this.getUserGroupList(id);
      this.editGrantUserGroupVisible = true;
    },
    // 授权用户组-确认
    editGrantUserGroupSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          userEditBatchUserGroupApi(this.form).then((res) => {
            this.editGrantUserGroupVisible = false;
          });
        } else {
          return false;
        }
      });
    },
    handleEditOrgUser() {
      if (this.$refs.form != undefined) {
        this.$refs["form"].resetFields();
      }
      this.userList = [];

      Promise.all([
        departmentListByUserIdApi(),
        positionListByUserIdApi(),
      ]).then(([departments, positions]) => {
        const formData = Object.assign({
          departments: departments?.bizData,
          departmentIds: [],
          positions: positions?.bizData,
          positionIds: [],
        });
        if (formData.departments !== null) {
          formData.departmentIds = getTreeByCheck(formData.departments).map(
              (item) => item.id
          );
        }
        if (formData.positions !== null) {
          formData.positionIds = formData.positions
              .filter((item) => item.checked)
              .map((item) => item.id);
        }
        this.form = formData;
      });

      this.editOrgUserVisible = true;
    },
    handleEnter(event) {
      let param = event.target.value;
      userListByConditionApi({param}).then((res) => {
        this.userList = res?.bizData;
      });
    },
    editOrgUserSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const data = createObjectBase(this.form, Object.keys(obj));
          const {departmentTree} = this.$refs;
          data.departmentIds = getSelectIds(departmentTree);
          userSaveOrgUserApi(data).then((res) => {
            this.editOrgUserVisible = false;
            this.getData();
          });
        } else {
          return false;
        }
      });
    },
    // 分页导航
    handlePageChange(val) {
      this.query.current = val;
      this.getData();
    },
  },
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
